﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using RFIDStockManagement.BLL;
using RFIDStockManagement.Common.Public.Enums;
using RFIDStockManagement.Common.Public;
using System.Threading;
using RFIDStockManagement.Common.Public.SQLLite;
using RFIDStockManagement.Model.Public;
using IOReadWriter;

namespace RFIDStockManagement.Client.IOStock
{
    public partial class OutStockList : XtraUserControl, IStockContainer
    {
        private RfidSpeedwayReader m_RfidReader = null;
        private RfidWriter m_RfidWriter = null;
        private RUser m_CurUser;
        private DataTable m_ItemList = new DataTable();
        private DataTable m_StockList = new DataTable();
        private DataTable m_GridData = new DataTable();

        public OutStockList(RUser logUser)
        {
            m_CurUser = logUser;
            InitializeComponent();
        }

        private void OutStockList_Load(object sender, EventArgs e)
        {
            try
            {
                m_RfidWriter = new RfidWriter(this, EnumIOStockOperate.OutStock);
                txtUser.Text = m_CurUser.LogName;
                txtTime.Text = DateTime.Now.ToString(PublicConst.LongTimeFormater);
                LoadInitData();
            }
            catch (Exception ex)
            {
                AlertForm.ShowError(ex.Message);
            }
        }
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                #region 验证数据
                if (cbbStock.SelectedIndex < 0)
                {
                    AlertForm.ShowMessage("仓库不能为空");
                    return;
                }
                if (txtOutStockPerson.Text.Trim().Length == 0)
                {
                    AlertForm.ShowMessage("领用人不能为空");
                    return;
                }
                if (m_GridData.Rows.Count == 0)
                {
                    AlertForm.ShowMessage("出库列表不能为空");
                    return;
                }

                #endregion

                if (AlertForm.Confirm("确定提交出库吗？"))
                {
                    Stop(false);
                    OutStockDataBuilder dataBuilder = new OutStockDataBuilder();
                    dataBuilder.BillerID = m_CurUser.ID;
                    dataBuilder.OutStockPerson = txtOutStockPerson.Text.Trim();
                    dataBuilder.Note = txtNote.Text.Trim();
                    dataBuilder.StockID = m_StockIndex[cbbStock.SelectedIndex];
                    //if (cbbSupplier.SelectedIndex >= 0)
                    //{
                    //    dataBuilder.SupplierId = m_SupplierIndex[cbbSupplier.SelectedIndex];
                    //}
                    string sql = "SELECT FItemID,FUnitID,FRfid FROM OutStock";
                    SQLiteDBHelper dbHealper = new SQLiteDBHelper(RfidWriter.DbPath);
                    DataTable dtRfid = dbHealper.ExecuteDataTable(sql, null);
                    if (dtRfid != null && dtRfid.Rows.Count > 0)
                    {
                        foreach (DataRow row in dtRfid.Rows)
                        {
                            DataRow itemRow = null;
                            DataRow[] rows = m_GridData.Select(string.Format("FItemID={0} AND FUnitID={1}", row["FItemID"], row["FUnitID"]));
                            if (rows != null && rows.Length > 0)
                            {
                                itemRow = rows[0];
                            }
                            //DataRow itemRow = SearchItem(Convert.ToInt64(row["BaseRfid"]));
                            if (itemRow != null)
                            {
                                long itemId = Convert.ToInt64(row["FItemID"]);
                                long unitId = Convert.ToInt64(row["FUnitID"]);
                                dataBuilder.AddDetailInfo(itemId, 0,//Convert.ToInt64(itemRow["FStockPlaceID"]),
                                    unitId, row["FRfid"].ToString());
                            }
                        }
                    }
                    OutStockManager stockManager = new OutStockManager();
                    string errMsg = string.Empty;
                    stockManager.Save(dataBuilder.GetData(), out errMsg);
                    if (errMsg != string.Empty)
                    {
                        AlertForm.ShowError(errMsg);
                    }
                    else
                    {
                        m_GridData.Rows.Clear();
                        gridData.DataSource = m_GridData;
                        dbHealper.ExecuteNonQuery("DELETE FROM OutStock", null);
                    }
                }
            }
            catch (Exception ex)
            {
                AlertForm.ShowError(ex.Message);
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (m_RfidReader == null)
                {
                    string[] readerCfg = SpeedwayPublicFunction.GetOutStockSpeedwayCfg();
                    if (readerCfg == null)
                    {
                        AlertForm.ShowMessage("Speedway配置不正确");
                        return;
                    }
                    m_RfidReader = new RfidSpeedwayReader(readerCfg[0], readerCfg[1], EnumIOStockOperate.OutStock);
                }

                Start();
                btnStart.Enabled = false;
                btnClear.Enabled = false;
                btnSubmit.Enabled = false;
                btnStop.Enabled = true;
            }
            catch (Exception ex)
            {
                AlertForm.ShowError(ex.Message);
            }
        }
        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                Stop(false);
                btnStop.Enabled = false;
                btnStart.Enabled = true;
                btnClear.Enabled = true;
                btnSubmit.Enabled = true;
            }
            catch (Exception ex)
            {
                AlertForm.ShowError(ex.Message);
            }
        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            try
            {
                m_GridData.Rows.Clear();
                gridData.DataSource = m_GridData;
                SQLiteDBHelper dbHealper = new SQLiteDBHelper(RfidWriter.DbPath);
                dbHealper.ExecuteNonQuery("DELETE FROM OutStock", null);
            }
            catch (Exception ex)
            {
                AlertForm.ShowError(ex.Message);
            }
        }
        /// <summary>
        /// 初始化物料信息
        /// </summary>
        private void LoadInitData()
        {
            gridView.ShowLoadingPanel();
            ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state)
            {
                try
                {
                    DataTable dtItem = IOStockBLL.GetItemUnit();
                    if (dtItem != null)
                    {
                        m_ItemList = dtItem;
                    }
                    DataTable dtStockList = BasicInfoManager.GetList(null, EnumBasicInfo.Stock);
                    if (dtStockList != null)
                    {
                        m_StockList = dtStockList;
                    }

                    string sql = "SELECT FItemID,FUnitID, COUNT(1) FCount FROM OutStock GROUP BY FItemID,FUnitID";
                    SQLiteDBHelper dbHealper = new SQLiteDBHelper(RfidWriter.DbPath);
                    DataTable dtRfid = dbHealper.ExecuteDataTable(sql, null);
                    if (dtRfid != null && dtRfid.Rows.Count > 0)
                    {
                        foreach (DataRow row in dtRfid.Rows)
                        {
                            AddGridData(Convert.ToInt64(row["FItemID"]), Convert.ToInt64(row["FUnitID"]), Convert.ToInt32(row["FCount"]));
                        }

                    }

                    LoadInitDataDelegate delegateMothod = new LoadInitDataDelegate(LoadInitDataHandler);
                    this.Invoke(delegateMothod);
                }
                finally
                {
                    gridView.HideLoadingPanel();
                }
            }));
        }
        private delegate void LoadInitDataDelegate();
        private Dictionary<int, long> m_StockIndex = new Dictionary<int, long>();
        private Dictionary<int, long> m_SupplierIndex = new Dictionary<int, long>();
        private void LoadInitDataHandler()
        {
            gridData.DataSource = m_GridData;
            if (m_StockList.Rows.Count > 0)
            {
                cbbStock.Properties.BeginUpdate();
                foreach (DataRow row in m_StockList.Rows)
                {
                    int index = cbbStock.Properties.Items.Add(string.Format("{0}({1})", row["FName"], row["FNumber"]));
                    long id = long.Parse(row["FID"].ToString());
                    m_StockIndex[index] = id;
                }
                cbbStock.Properties.EndUpdate();
            }
        }
        private void AddGridData(long itemId, long unitId, int iCount)
        {
            if (m_GridData.Columns.Count == 0)
            {
                m_GridData.Columns.Add("FName", typeof(string));
                m_GridData.Columns.Add("FNumber", typeof(string));
                //m_GridData.Columns.Add("FStockName", typeof(string));
                //m_GridData.Columns.Add("FStockPlaceName", typeof(string));
                m_GridData.Columns.Add("FItemId", typeof(string));
                m_GridData.Columns.Add("FUnitId", typeof(long));
                m_GridData.Columns.Add("FUnitName", typeof(string));
                m_GridData.Columns.Add("FCount", typeof(int));
                m_GridData.Columns.Add("FDateTime", typeof(string));
            }
            DataRow itemRow = SearchItem(itemId, unitId);
            if (itemRow != null)
            {
                DataRow[] rows = m_GridData.Select(string.Format("FItemId={0} AND FUnitId={1}", itemId, unitId));
                if (rows != null && rows.Length > 0)
                {
                    int iOldCount = Convert.ToInt32(rows[0]["FCount"]);
                    rows[0]["FCount"] = iOldCount + iCount;
                }
                else
                {
                    DataRow newRow = m_GridData.NewRow();
                    newRow["FName"] = itemRow["FName"];
                    newRow["FNumber"] = itemRow["FNumber"];
                    //newRow["FStockName"] = itemRow["FStockName"];
                    //newRow["FStockPlaceName"] = itemRow["FStockPlaceName"];
                    newRow["FItemId"] = itemId;
                    newRow["FUnitId"] = unitId;
                    newRow["FUnitName"] = itemRow["FUnitName"];
                    newRow["FCount"] = iCount;
                    newRow["FDateTime"] = DateTime.Now.ToString(PublicConst.LongTimeFormater);
                    m_GridData.Rows.InsertAt(newRow, 0);
                }
            }
        }
        private DataRow SearchItem(long itemId, long unitId)
        {
            DataRow result = null;
            DataRow[] rows = m_ItemList.Select(string.Format("FItemID={0} AND FUnitID={1}", itemId, unitId));
            if (rows != null && rows.Length > 0)
            {
                result = rows[0];
            }

            return result;
        }

        private void Start()
        {
            m_RfidReader.StartRead();
            m_RfidWriter.StartWrite();
        }
        public void Stop(bool disConnect)
        {
            if (m_RfidReader != null)
            {
                m_RfidReader.StopRead(disConnect);
            }
            if (m_RfidWriter != null)
            {
                m_RfidWriter.StopWrite();
            }
        }

        #region IStockContainer Member

        public bool IsShowed { get; set; }
        public void ShowRfidData(List<RfidDataInfo> lstResult)
        {
            Dictionary<string, int> dctRfid = new Dictionary<string, int>();
            foreach (RfidDataInfo item in lstResult)
            {
                string baseRfid = string.Format("{0}_{1}", item.ItemId, item.UnitId);
                int iCount = 0;
                dctRfid.TryGetValue(baseRfid, out iCount);
                iCount++;
                dctRfid[baseRfid] = iCount;
            }
            AppendGridDataDelegate delegateMothod = new AppendGridDataDelegate(AppendGridDataHandler);
            this.Invoke(delegateMothod, dctRfid);
        }
        private delegate void AppendGridDataDelegate(Dictionary<string, int> dctRfid);
        private void AppendGridDataHandler(Dictionary<string, int> dctRfid)
        {
            try
            {
                gridData.BeginUpdate();
                foreach (KeyValuePair<string, int> item in dctRfid)
                {
                    string[] arr = item.Key.Split('_');
                    AddGridData(long.Parse(arr[0]), long.Parse(arr[1]), item.Value);
                }
                //gridData.DataSource = m_GridData;
                gridData.EndUpdate();
            }
            finally
            {
                IsShowed = true;
            }
        }

        #endregion




    }
}
